﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sashulin;

namespace JianKangPingTaiBrowser
{
    public partial class Form1 : Form
    {
        readonly ChromeWebBrowser _chromeWebBrowser1 = new ChromeWebBrowser();
        public Form1()
        {

            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            var settings = new CSharpBrowserSettings
            {
                //DefaultUrl = System.IO.Directory.GetCurrentDirectory() + "\\index.html",
                DefaultUrl = GetUrl(),
                CachePath = @"C:\temp\caches"
            };
            _chromeWebBrowser1.Initialize(settings);

        }
        /// <summary>
        /// 还参数启动
        /// </summary>
        /// <param name="args"></param>
        public Form1(string[] args)
        {
          
            InitializeComponent();
            var settings = new CSharpBrowserSettings();
            if (!string.IsNullOrWhiteSpace(args[0]))
            {
                settings.DefaultUrl = args[0];
               
                //MessageBox.Show(args[0]);
            }
            else
            {
                MessageBox.Show("参数Url没有获取到");
                var url = GetUrl();
                settings.DefaultUrl = url;
            }
            settings.CachePath = @"C:\temp\caches";
            _chromeWebBrowser1.Initialize(settings);

        }
        private void Form1_Load(object sender, EventArgs e)
        {
            #region ChromeWebBrowser初始化
            this.Dock = DockStyle.Fill;
            //this.tabControl1.Dock = DockStyle.Fill;
            _chromeWebBrowser1.ContextMenu=new ContextMenu();
            //MenuItem aaa=new MenuItem("刷新");
            //aaa.Click+=new EventHandler(this.RefreshPage);
            _chromeWebBrowser1.ContextMenu.MenuItems.Add(new MenuItem("刷新", new EventHandler(this.RefreshPage)));
            //_chromeWebBrowser1.ContextMenu.MenuItems.Add(new MenuItem("获取输入框", new EventHandler(this.AlertTest)));
            //panel1.Size=new Size(1200, 700);
            _chromeWebBrowser1.Dock = DockStyle.Fill;
            _chromeWebBrowser1.AddPluginDir(@"\plugins");
            this.panel1.Controls.Add(this._chromeWebBrowser1);
            //this.tabPage1.Controls.Add(this._chromeWebBrowser1);
            this._chromeWebBrowser1.BackColor = System.Drawing.SystemColors.ActiveBorder;
            this._chromeWebBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
            this._chromeWebBrowser1.Location = new System.Drawing.Point(3, 3);
            this._chromeWebBrowser1.Name = "chromeWebBrowser1";
            this._chromeWebBrowser1.Size = new System.Drawing.Size(591, 285);
            this._chromeWebBrowser1.TabIndex = 0;
            this._chromeWebBrowser1.BrowserTitleChange += new Sashulin.TitleChangeEventHandler(this.chromeWebBrowser1_BrowserTitleChange);
            this._chromeWebBrowser1.BrowserUrlChange += new Sashulin.UrlChangeEventHandler(this.chromeWebBrowser1_BrowserUrlChange);
            this._chromeWebBrowser1.BrowserNewWindow += new Sashulin.NewWindowEventHandler(this.chromeWebBrowser1_BrowserNewWindow);

            #endregion

            #region 系统时间
            this.toolStripStatusLabel1.Text = @"当前系统时间：" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            this.timer1.Interval = 1000;
            this.timer1.Start();
            #endregion

            #region 加载左下角菜单
            LoadMenu();
            #endregion
            #region 读取初始化参数

            var ismax = Boolean.Parse(GetAppConfig("max"));
            if (ismax)
            {
                this.WindowState = FormWindowState.Maximized;
            }
            else
            {
                this.Width = int.Parse(GetAppConfig("width"));//winform宽
                this.Height = int.Parse(GetAppConfig("height"));//winform高
            }

            #endregion
        }

        private void RefreshPage(object sender, EventArgs e)
        {
            _chromeWebBrowser1.Reload(false);
        }

        private void AlertTest(object sender,EventArgs e)
        {
            //MessageBox
            //var doc = _chromeWebBrowser1.Document;
            //doc.
            //doc.GetElementById("TextBoxEx1");
            //MessageBox.Show(doc.GetElementById("TextBoxEx1").ToString());
            //return "return : Js call";
        }
        #region 读取网页Title
        private void chromeWebBrowser1_BrowserTitleChange(object sender, TitleEventArgs e)
        {
            //TabPage page = ((ChromeWebBrowser)sender).Parent as TabPage;
            //page.Text = e.Title;
        }
        #endregion
        #region 读取网页地址
        private void chromeWebBrowser1_BrowserUrlChange(object sender, UrlChangeEventArgs e)
        {
            //textBox1.Text = e.Url;
        }
        #endregion

        #region 打开新页
        delegate void NewPageListener(string url, object request);
        private void chromeWebBrowser1_BrowserNewWindow(object sender, NewWindowEventArgs e)
        {
            if (this.InvokeRequired)
            {
                NewPageListener a = new NewPageListener(NewPage);
                this.Invoke(a, new object[] { e.NewUrl, e.Request });
            }
            else
            {
                NewPage(e.NewUrl, e.Request);
            }
        }
        object aaa;
        ChromeWebBrowser browser1;
        private void NewPage(string newUrl, object req)
        {
            TabPage newPage = new TabPage(newUrl);
            //tabControl1.TabPages.Add(newPage);
            //tabControl1.SelectTab(newPage);
            CSharpBrowserSettings settings = new CSharpBrowserSettings();
            //settings.UserAgent = "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19";
            settings.CachePath = @"C:\temp\caches";
            ChromeWebBrowser browser = new ChromeWebBrowser();
            browser.BrowserNewWindow += new NewWindowEventHandler(chromeWebBrowser1_BrowserNewWindow);
            browser.BrowserTitleChange += new TitleChangeEventHandler(chromeWebBrowser1_BrowserTitleChange);
            browser.Initialize(settings);
            newPage.Controls.Add(browser);
            browser.Validate();
            browser.Dock = DockStyle.Fill;
            if (!newUrl.Contains("&"))
                browser.OpenUrl(newUrl);
            else
                browser.OpenUrl(req);
            aaa = req;
            browser1 = browser;
        }
        #endregion
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.toolStripStatusLabel1.Text = @"当前系统时间：" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
        }
        #region JavaScript 弹窗
        public string ShowMessage(string msg)
        {
            MessageBox.Show(msg);
            return "return : Js call";
        }
        #endregion

        #region 配置文件读取，app.config和xml
        ///<summary> 
        ///返回*.exe.config文件中appSettings配置节的value项  
        ///</summary> 
        ///<param name="strKey"></param> 
        ///<returns></returns> 
        public static string GetAppConfig(string strKey)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == strKey)
                {
                    return config.AppSettings.Settings[strKey].Value.ToString();
                }
            }
            return null;
        }
        /// <summary>
        /// 菜单读取
        /// </summary>
        private void LoadMenu()
        {
            Menu menu = new Menu();
            menu.Path = System.Windows.Forms.Application.StartupPath + "\\Menu.xml";
            if (menu.FileExit())
            {
                menu.LoadAllMenu(toolStripDropDownButton1);
            }
            else
            {
                MessageBox.Show(menu.Path);
                MessageBox.Show("XML文件加载失败！");
            }
        }
        private string GetUrl()
        {
            var url = GetAppConfig("url");
            if (url.Contains(":\\"))
            {

            }
            else if (!url.Contains("http://"))
            {
                url = "http://" + url;
            }
            return url;
        }
        #endregion

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

       
        private void 关于ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var ver = "";
            ver = "程序集版本：" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + "\n";
            //ver += "文件版本：" + Application.ProductVersion.ToString() + "\n";
            //ver += "部署版本：" + System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
            MessageBox.Show(ver);
        }
    }
}
